package com.jason.www.activity;

import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jason.www.R;
import com.jason.www.base.BaseActivity;
import com.jason.www.http.response.AccessTokenEntity;
import com.jason.www.http.response.IdCardOCREntity;
import com.jason.www.utils.GlideEngine;
import com.jason.www.utils.GlideUtils;
import com.jason.www.utils.GsonUtils;
import com.jason.www.utils.LogUtils;
import com.jason.www.utils.OKHttpUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Response;

public class OCRActivity extends BaseActivity {
    private ImageView imageView;
    private TextView textView;
    private RadioGroup radioGroup;
    private final String IDCARD_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
    private final String GET_ACCESSTOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private final String CLIENT_ID = "NLZr1ecPnssTnADWD8rxTg25";
    private final String CLIENT_SECRET = "wgOZGbFhjFuwHitUixNiKuAVxuRmKWZK";
    private String accessToken = null;
    //默认人像面，front-人像面，back-国徽面
    private String id_card_side = "front";
    private String imagePath = null;
    private String testNetImageUrl = "https://baidu-ai.bj.bcebos.com/ocr/idcard.jpeg";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ocractivity;
    }

    @Override
    protected void initView() {
        super.initView();
        imageView = findViewById(R.id.iv_show);
        textView = findViewById(R.id.tv_show);
        radioGroup = findViewById(R.id.rg_select);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_country) {
                    id_card_side = "back";
                } else if (checkedId == R.id.rb_face) {
                    id_card_side = "front";
                }
            }
        });
        getAccessToken();
    }

    private void getAccessToken() {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("grant_type", "client_credentials");
        builder.add("client_id", CLIENT_ID);
        builder.add("client_secret", CLIENT_SECRET);
        OKHttpUtils.post(GET_ACCESSTOKEN_URL, null, builder.build(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                LogUtils.i("获取的accesstoken\n" + string);
                AccessTokenEntity accessTokenEntity = GsonUtils.getGson().fromJson(string, AccessTokenEntity.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        accessToken = accessTokenEntity.accessToken;
                    }
                });
            }
        });
    }

    public void selectPic(View view) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                //不支持gif
                .isGif(false)
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.SINGLE)
                .isPreviewImage(true)
                .isCompress(true)
                .minimumCompressSize(200)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        if (result == null) {
                            return;
                        }
                        imagePath = result.get(0).getCompressPath();
                        GlideUtils.loadLocalImage(imageView, imagePath);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    public void startOCR(View view) {
        if (accessToken == null) {
            showToast("accessToken未获取到");
            return;
        }
        if (imagePath == null) {
            showToast("请先选择照片");
            return;
        }
        showLoading("识别中...");
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                String imageBase64 = imageToBase64(imagePath);
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("access_token", accessToken);
                builder.add("image", imageBase64);
                //builder.add("url", testNetImageUrl);
                builder.add("id_card_side", id_card_side);
                Headers.Builder headerBuilder = new Headers.Builder();
                headerBuilder.add("Content-Type", "application/x-www-form-urlencoded");
                OKHttpUtils.post(IDCARD_URL, headerBuilder.build(), builder.build(), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        showToast(e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                hideLoading();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().string();
                        LogUtils.i("识别结果\n" + string);
                        IdCardOCREntity idCardOCREntity = GsonUtils.getGson().fromJson(string, IdCardOCREntity.class);
                        IdCardOCREntity.WordsResultDTO wordsResult = null;
                        if (idCardOCREntity != null) {
                            wordsResult = idCardOCREntity.wordsResult;
                        }
                        StringBuilder sb = new StringBuilder();
                        if (wordsResult != null) {
                            sb.append("姓名：").append(wordsResult.name.words).append("\n")
                                    .append("性别：").append(wordsResult.sex.words).append("\n")
                                    .append("身份证号：").append(wordsResult.idNumber.words).append("\n")
                                    .append("出生日期：").append(wordsResult.birth.words).append("\n")
                                    .append("住址：").append(wordsResult.address.words).append("\n")
                                    .append("民族：").append(wordsResult.nation.words).append("\n");
                        } else {
                            sb.append("未识别到身份证信息");
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText("识别结果:\n" + sb);
                                hideLoading();
                            }
                        });
                    }
                });
                executorService.shutdownNow();
            }
        });
    }

    private static String imageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        InputStream in = null;
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.encode(Objects.requireNonNull(data), Base64.DEFAULT);
        try {
            return new String(encode, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}